<!DOCTYPE html>
<html lang="en">
<head>
    <title>开通车联网</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style type="text/css">
        td {
            height: 30px;
        }

        .td-right {
            width: 22%;
        }

        .td-left {
            width: 28%;
        }

        body {
            background-color: #efefef;
        }

        table, table tr th, table tr td {
            border: 1px solid rgba(68, 67, 72, 0.57);
        }

        table {
            margin-top: 16px;
            margin-bottom: 8px;
            margin-left: auto;
            margin-right: auto;
            width: 100%;
        }

        h2 {
            margin: auto;
            padding: 5px 5px;
            background-color: #cecfce;
        }

        input, select {
            padding: 3px 3px;
            margin: 6px 6px;
        }

        easyui-combobox {
            height: 24px;
        }

        .td-right {
            text-align: right;
            background-color: #f7f3f7;
        }

        .td-left {
            text-align: left;
            background-color: #ffffff;
        }

        body {
            min-width: 850px;
        }

        .container {
            width: 849px;
            margin: auto;
        }
        span.content {
            margin-left: 10px;
            font-size: 14px;
        }
        #submit {
            background-color: rgba(51, 153, 255, 1);
            width: 300px;
            height: 26px;
            display: block;
            margin: 5px auto;
            border-radius: 5px;
            cursor: pointer;
            line-height: 26px;
            text-decoration: none;
            color: white;
            text-align: center;
            font-size: 12px;
        }
        #messageBox {
            padding: 0px 15px;
            min-width: 150px;
            height: 50px;
            background-color: #ddd;
            border-radius: 10px;
            line-height: 50px;
            border: #999 solid 1px;
            position: absolute;
            left: 40%;
            top: -70px;
            opacity: 0.8;
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <form id="usersDataForm" method="post" novalidate>
        <table style="border-collapse: collapse;">
            <tr>
                <td colspan="4">
                    <h2>车辆信息</h2>
                </td>
            </tr>
            <tr>
                <td class="td-right">
                    <span>品牌：</span>
                </td>
                <td class="td-left">
                    <span class="content" id="vtypeBrand"></span>
                </td>
                <td class="td-right">
                    <span>配置：</span>
                </td>
                <td class="td-left">
                    <span class="content" id="vtypeConfig"></span>
                </td>
            </tr>
            <tr>
                <td class="td-right">
                    <span>车架号：</span>
                </td>
                <td class="td-left">
                    <span class="content" id="vin"></span>
                </td>
                <td class="td-right">
                    <span>发动机号：</span>
                </td>
                <td class="td-left">
                    <span class="content" id="engineno"></span>
                </td>
            </tr>
            <tr>

                <td class="td-right">
                    <span>颜色：</span>
                </td>
                <td class="td-left">
                    <span class="content" id="color"></span>
                </td>
                <td class="td-right">
                    <span>T服务状态：</span>
                </td>
                <td class="td-left">
                    <span class="content" id="tsstate"></span>
                    <input type="button" id="refreshSimStatus" onclick="getVehicleInfo()" value="重试" />
                </td>
            </tr>
            <tr>
                <td colspan="4">
                    <h2>使用人信息</h2>
                </td>
            </tr>
            <tr>
                <td class="span-width tdHeight td-right">
                    <span style="color: red">*</span><span>使用人手机号：</span>
                </td>
                <td class="input-td-width tdHeight td-left">
                    <input id="phone" name="phone" autocomplete="off"/>
                </td>
                <td class="span-width tdHeight td-right">
                    <input type="button" id="sendSmsBtn" onclick="codeMessage('01')"
                           style="width: 165px"
                           value="检测并获取短信验证码" />
                </td>
                <td class="input-td-width tdHeight td-left">
                    <input id="CODE" name="CODE"
                           style="width:50px;"
                           class="easyui-validatebox content-width" type="text"
                           data-options="required:true"
                           placeholder="验证码"
                           autocomplete="off"/>
                    <div style="display:inline-block;color:grey;font-size: 13px">验证码有效时间为5分钟</div>
                </td>
            </tr>
            <tr>
                <td class="span-width tdHeight td-right">
                    <span style="color: red">*</span><span>姓名：</span>
                </td>
                <td class="input-td-width tdHeight td-left">
                    <input id="name" name="name" autocomplete="off"/>
                </td>
                <td class="span-width tdHeight td-right">
                    <span style="color: red">*</span><span>性别：</span>
                </td>
                <td class="input-td-width tdHeight td-left">
                    <label><input type="radio" name="sex" value="1" autocomplete="off" checked>男</label>
                    <label><input type="radio" name="sex" value="0" autocomplete="off">女</label>
                </td>
            </tr>
            <tr>
                <td class="span-width tdHeight td-right">
                    <span style="color: red">*</span><span>证件类型：</span>
                </td>
                <td class="input-td-width tdHeight td-left">
                    <select id="idcardType" name="idcardType" style="width: 180px" autocomplete="off">
                        <option value=""></option>
                        <option value="0">身份证</option>
                        <option value="1">企业代码证</option>
                        <option value="2">其他</option>
                        <option value="3">营业执照</option>
                    </select>
                </td>
                <td class="span-width tdHeight td-right">
                    <span style="color: red">*</span><span>证件号码：</span>
                </td>
                <td class="input-td-width tdHeight td-left">
                    <input id="idcardNo" name="idcardNo" autocomplete="off"/>
                </td>
            </tr>
            <tr>
                <td class="span-width tdHeight td-right">
                    <span style="color: red">*</span><span>紧急联系人手机号：</span>
                </td>
                <td class="input-td-width tdHeight td-left">
                    <input id="secContPhone" name="secContPhone" autocomplete="off"/>
                </td>
                <td class="span-width tdHeight td-right">
                    <span style="color: red">*</span><span>车主类型：</span>
                </td>
                <td class="input-td-width tdHeight td-left">
                    <label><input type="radio" name="userType" value="0" autocomplete="off" checked>个人车主</label>
                    <label><input type="radio" name="userType" value="1" autocomplete="off">单位车主</label>
                </td>
            </tr>
            <tr>
                <td class="span-width tdHeight td-left" colspan="4">
                    <a id ="submit" href="javascript:void(0)" class="button button-rounded button-flat-primary" onclick="submit();">提 交</a>
                </td>
            </tr>
        </table>
        <span style="font-size: 12px; color: red">每月26日为通讯运营商结算日，当天不能开通车联网服务，如必需，请联系400-666-6677</span>
    </form>
    <div id="messageBox"></div>
</div>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="md5.js"></script>
<script type="text/javascript" src="url.js"></script>
<script type="text/javascript">
    window.onload = function () {
        $('#phone').val('')
        $('#CODE').val('')
        $('#name').val('')
        $('#idcardType').val('')
        $('#idcardNo').val('')
        $('#secContPhone').val('')
        $(':radio[name="sex"][value="1"]').prop('checked', 'checked')
        $(':radio[name="userType"][value="0"]').prop('checked', 'checked')
    }
    jQuery.support.cors = true; // IE9兼容ajax跨域
    var paramsStr = window.location.search
    var baseUrl = url || 'http://yuntest.gwm.com.cn:86'//'http://tsp_sub.gwm.com.cn' //
    var params = {
        vin: paramsStr.split('vin=')[1] ? paramsStr.split('vin=')[1].split('&')[0] : '',
        dealerNum: paramsStr.split('dealerNum=')[1] ? paramsStr.split('dealerNum=')[1].split('&')[0] : '',
        account: paramsStr.split('account=')[1] ? paramsStr.split('account=')[1].split('&')[0] : '',
        token: paramsStr.split('token=')[1] ? paramsStr.split('token=')[1].split('&')[0] : ''
    }
    var token2 = md5(params.dealerNum + decodeURI(params.account) + new Date().getFullYear() + addZero((new Date().getMonth() + 1).toString()) + addZero(new Date().getDate().toString()))
    var codeClock = 0
    var userId = ''

    // 校验参数token是否正确MD5加密，格式 130620管理员20190716
    if (token2.toUpperCase() !== params.token) {
        window.location.href = 'error.html'
    } else {
        var colorObj = {}
        var tsstateObj = {}
        getAllInfo()
    }

    // 获取与车辆有关信息
    function getAllInfo () {
        // 获取车辆颜色列表
        $.ajax({
            async: false,
            type: 'GET',
            contentType: "application/json;charset=utf-8",
            url: baseUrl + '/boss/openapi/basedata/getCodeList?codeKind=Veh_Color',
            data: {
                dealerNum: params.dealerNum,
                account: params.account,
                token: params.token
            },
            dataType: 'json',
            success: function (data) {
                if (data.code === 200) {
                    colorObj = data.data
                }
            },
            error: function (e) {
                requestError(e)
            }
        })
        // 获取T服务状态列表
        $.ajax({
            async: false,
            type: 'GET',
            contentType: "application/json;charset=utf-8",
            url: baseUrl + '/boss/openapi/basedata/getCodeList?codeKind=Code_tsState',
            data: {
                dealerNum: params.dealerNum,
                account: params.account,
                token: params.token
            },
            dataType: 'json',
            success: function (data) {
                if (data.code === 200) {
                    tsstateObj = data.data
                }
            },
            error: function (e) {
                requestError(e)
            }
        })
        getVehicleInfo()
    }
    // 根据vin号获取车辆信息
    function getVehicleInfo () {
        $('#tsstate').html('') // 为了T服务状态有刷新的感觉
        $.ajax({
            async: true,
            type: 'GET',
            contentType: "application/json;charset=utf-8",
            url: baseUrl + '/boss/openapi/vehicle/getVehicleAllInfoByVin',
            data: {
                vin: params.vin,
                dealerNum: params.dealerNum,
                account: params.account,
                token: params.token
            },
            dataType: 'json',
            success: function (data) {
                if (data.code === 200 && data.data) {
                    if (data.data.vehicleDto) {
                        $('#vtypeBrand').html(data.data.vehicleDto.vtypeBrand)
                        $('#vtypeConfig').html(data.data.vehicleDto.vtypeConfig)
                        $('#vin').html(data.data.vehicleDto.vin)
                        $('#engineno').html(data.data.vehicleDto.engineno)
                        $('#color').html(colorObj[data.data.vehicleDto.color])
                        $('#purchaseDate').html(dateToString(data.data.vehicleDto.purchaseDate))
                    }
                    if (data.data.serviceNoPwdDto) {
                        $('#tsstate').html(tsstateObj[data.data.serviceNoPwdDto.tsstate])
                    }
                    if (data.data.simDto) {
                        $('#iccid').html(data.data.simDto.iccid)
                    }
                }
            },
            error: function (e) {
                requestError(e)
            }
        })
    }
    // 发送和校验验证码短信
    function codeMessage (type, code) {
        if ($('#tsstate').html() !== '待销售状态' && $('#tsstate').html() !== '已入库状态') {
            showMessage('只有已入库和待销售状态的车辆可以开通车联网')
            return
        }
        if (codeClock > 0 && type === '01') {
            return
        }
        var phone = $('#phone').val()
        if (!phone.match(/^1[3456789]\d{9}$/)) {
            showMessage('输入手机号有误')
            $('#name').val('')
            $('select[name="idcardType"]').get(0).selectedIndex = 0
            $('#idcardNo').val('')
            $('#secContPhone').val('')
            return
        }
        // 根据输入手机号，如果为已存在用户，则把用户信息带出来
        if (type === '01') {
            getUserInfoByPhone()
        }/* else {
            openVehicle()
            return
        } */
        $.ajax({
            async: true,
            type: 'GET',
            contentType: "application/json;charset=utf-8",
            url: baseUrl + '/boss/openapi/tsp/request4Tsp',
            data: {
                phone:$('#phone').val(),
                code: code || '0',
                requestType: type,
                dealerNum: params.dealerNum,
                account: params.account,
                token: params.token
            },
            dataType: 'json',
            success: function (data) {
                if (data.data.result === 'success') {
                    if (type === '01') {
                        showMessage('验证码发送成功')
                        countSecond()
                    } else {
                        // 开通车联网
                        openVehicle()
                    }
                } else {
                    if (type === '01') {
                        showMessage('验证码发送失败')
                        countSecond()
                    } else {
                        showMessage('验证码不正确')
                    }
                }
            },
            error: function (e) {
                if (type === '01') {
                    showMessage('验证码发送失败')
                    countSecond()
                } else {
                    showMessage('验证码不正确')
                    countSecond()
                }
                requestError(e)
            }
        })
    }
    /**
     * 开通车联网
     */
    function openVehicle () {
        var dataObj = {
            phone: $('#phone').val(),
            name: $('#name').val(),
            sex: $(':radio[name="sex"]:checked').val(),
            idcardType: $('select[name="idcardType"]').val(),
            idcardNo: $('#idcardNo').val(),
            secContPhone: $('#secContPhone').val(),
            userType: $(':radio[name="userType"]:checked').val(),
            vin: params.vin,
            purchaseDate: new Date().getTime()
        }
        if (userId && userId !== '') {
            dataObj.userId = userId
        }
        $.ajax({
            async: false,
            type: 'POST',
            contentType: "application/json;charset=utf-8",
            url: baseUrl + '/boss/openapi/vehicle/add/addVehicleOwner?' + 'dealerNum=' + params.dealerNum + '&account=' + params.account + '&token=' + params.token,
            data: JSON.stringify(dataObj),
            dataType: 'json',
            success: function (data) {
                if (data && data.code === 200) {
                    showMessage('车联网开通成功')
                } else {
                    showMessage('车联网开通失败')
                }
            },
            error: function (e) {
                showMessage(e.responseJSON.message)
            }
        })
    }
    /**
     * 更换手机号
     */
    function submit() {
        if (!$('#phone').val().match(/^1[3456789]\d{9}$/)) {
            showMessage('输入手机号有误')
            return
        }
        if (!$('#name').val() || $('#name').val() === '') {
            showMessage('请输入车主姓名')
            return
        }
        if (!$('select[name="idcardType"]').val() || $('select[name="idcardType"]').val() === '') {
            showMessage('请选择证件类型')
            return
        }
        if ($('#idcardNo').val().length < 1 || $('#idcardNo').val().length > 30) {
            showMessage('证件号码必须1-30位')
            return
        }
        if (!$('#secContPhone').val().match(/^1[3456789]\d{9}$/)) {
            showMessage('紧急联系人手机号有误')
            return
        }
        codeMessage('02', $('#CODE').val())
    }
    // 请求报错
    function requestError (e) {
        console.log(e)
    }
    // 时间戳转字符串
    function dateToString (stamp) {
        if (stamp) {
            var date = new Date(stamp)
            return date.getFullYear() + '-' + addZero((date.getMonth() + 1).toString()) + '-' + addZero(date.getDate().toString())
        } else {
            return ''
        }
    }
    // 提示信息
    function showMessage (content) {
        if($('#messageBox').css('top') === '-70px') {
            $('#messageBox').html(content)
            $('#messageBox').animate({ top:'70px' })
            setTimeout(function () {
                $('#messageBox').animate({ top:'-70px' })
            }, 4000)
        }
    }
    // 发送验证码倒计时
    function countSecond () {
        codeClock = 30
        $('#sendSmsBtn').val('点击获取验证码（' + codeClock + '）')
        var tInterval = setInterval(function () {
            if (codeClock > 0) {
                codeClock--
                $('#sendSmsBtn').val('点击获取验证码（' + codeClock + '）')
            } else {
                $('#sendSmsBtn').val('点击获取验证码')
                clearInterval(tInterval)
            }
        }, 1000)
    }
    // 根据手机号查询用户信息
    function getUserInfoByPhone () {
        $.ajax({
            async: true,
            type: 'GET',
            contentType: "application/json;charset=utf-8",
            url: baseUrl + '/boss/openapi/owner/getOwnerByPhone',
            data: {
                phone: $('#phone').val(),
                dealerNum: params.dealerNum,
                account: params.account,
                token: params.token
            },
            dataType: 'json',
            success: function (data) {
                if (data && data.data && data.data.name) {
                    $('#name').val(data.data.name)
                    $('select[name="idcardType"]').get(0).selectedIndex = data.data.idcardType + 1
                    $('#idcardNo').val(data.data.idcardNo)
                    $('#secContPhone').val(data.data.secContPhone)
                    $(':radio[name="userType"]').eq(data.data.userType).prop("checked", true)
                    if (data.data.sex === 1) {
                        $(':radio[name="sex"]').eq(0).prop("checked", true)
                    } else if (data.data.sex === 0) {
                        $(':radio[name="sex"]').eq(1).prop("checked", true)
                    }
                    userId = data.data.keyid
                } else {
                    $('#name').val('')
                    $('select[name="idcardType"]').get(0).selectedIndex = 0
                    $('#idcardNo').val('')
                    $('#secContPhone').val('')
                    userId = ''
                }
            },
            error: function (e) {
                requestError(e)
            }
        })
    }
    // 月份日期补零
    function addZero (val) {
        return val.length === 1 ? '0' + val : val
    }

</script>

</body>
</html>
